/**
 * 
 */
package cn.sundat.web.action;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.sundat.model.User;
import cn.sundat.service.UserService;

/**
 * @author XIN
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<User> {
	private static final long serialVersionUID = 1L;
	

	@Resource(name = "userService")
	private UserService userService;
	private User user = new User();
	public User getModel() {
		return user;
	}


	public String add() throws Exception {
		userService.addUser(user);
		return NONE;
	}
	public String deluser() throws Exception {
		userService.delUser(user);
		return NONE;
	}
	public String edituser() throws Exception {
		userService.editUser(user);
		ActionContext.getContext().getSession().put("userInfo", user);
		return "toIndex";
	}
	public String findUserByPage() throws Exception {
		List<User> findUserByPage = userService.findUserByPage(1, 8);
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter writer = ServletActionContext.getResponse().getWriter();
		writer.print(JSONObject.valueToString(findUserByPage));
		writer.flush();
		writer.close();
		return NONE;
	}
	public String findUserById()throws Exception {
		Integer id=Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
		List<User> users=userService.findUserById(id);
		PrintWriter writer = ServletActionContext.getResponse().getWriter();
		writer.print(JSONObject.valueToString(users));
		writer.flush();
		writer.close();
		return NONE;
	}
	public String loginCheck()throws Exception {
		PrintWriter writer = ServletActionContext.getResponse().getWriter();
		String uname=ServletActionContext.getRequest().getParameter("username");
		String passWd=ServletActionContext.getRequest().getParameter("password");
		List<User> findUserByUnameAndPasswd = userService.findUserByUnameAndPasswd(uname, passWd);
		System.out.println(findUserByUnameAndPasswd.size());
		if (findUserByUnameAndPasswd.size()>0) {
			User user = findUserByUnameAndPasswd.get(0);
			ActionContext.getContext().getSession().put("userInfo", user);
			writer.print(1);
		}else {
			writer.print(0);
		}
		writer.flush();
		writer.close();
		return NONE;
	}
	public String logOut()throws Exception {
		ActionContext.getContext().getSession().remove("userInfo");
		return "login";
	}

}
